import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosRequestHeaders,
  InternalAxiosRequestConfig,
} from "axios";
import { ElMessage } from "element-plus";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/service-loading";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/http-enum";
import { LOGIN_URL } from "@/config/config";
import { checkStatus } from "@/api/helper/check-status";
import router from "@/router";
import { useUserStore } from "@/store/modules/user";
const store = useUserStore();
const config = {
  // 默认地址请求地址，可在 .env.*** 文件中修改
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 设置超时时间（10s）
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
};
let showLoading = true;
class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config);

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        // * 如果当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { headers: { noLoading: true } }来控制不显示loading，参见loginApi
        if (!showLoading) {
          config.headers.noLoading = true;
        } else {
          config.headers!.noLoading || showFullScreenLoading();
        }
        const token = store.$state.token;
        config.headers = {
          ...config.headers,
          Authorization: `${token}`,
        } as AxiosRequestHeaders;
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      },
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        // * 在请求结束后，并关闭请求 loading
        tryHideFullScreenLoading();
        // * 登陆失效（code == 401）
        if (data.code === ResultEnum.OVERDUE) {
          ElMessage.error(data.message);
          store.setToken("");
          router.replace(LOGIN_URL);
          return Promise.reject(data);
        } else if (data.code === ResultEnum.SUCCESS) {
          // * 成功请求
          return data;
        } else if (data instanceof Blob) {
          // * 成功请求

          return data;
        } else {
          ElMessage.error(data.message || "请求失败");
          return Promise.reject(data);
        }
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
        // 根据响应的错误状态码，做不同的处理
        if (response) {
          checkStatus(response.status);
          if (response.status === ResultEnum.OVERDUE) {
            store.setToken("tokenvalue");
            router.replace(LOGIN_URL);
            return Promise.reject(error);
          }
        }
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) router.replace("/500");
        return Promise.reject(error);
      },
    );
  }

  // * 常用请求方法封装
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    this.dealNoloading(_object);
    return this.service.get(url, { params, ..._object });
  }

  post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    this.dealNoloading(_object);
    return this.service.post(url, params, _object);
  }

  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    this.dealNoloading(_object);
    return this.service.put(url, params, _object);
  }

  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    this.dealNoloading(_object);
    return this.service.delete(url, { params, ..._object });
  }

  download(url: string, params?: object, _object = {}) {
    this.dealNoloading(_object);
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }

  // 是否需要添加loading
  dealNoloading(object: { noloading?: any }) {
    if (object && object.noloading) {
      if (object.noloading) {
        showLoading = false;
      } else {
        showLoading = true;
      }
    } else {
      showLoading = true;
    }
  }
}

export default new RequestHttp(config);
